package com.leyou.order.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.thrreadlocals.UserHolder;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.IdWorker;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.order.dto.CartDTO;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.entity.Order;
import com.leyou.order.entity.OrderDetail;
import com.leyou.order.entity.OrderLogistics;
import com.leyou.order.enums.OrderStatusEnum;
import com.leyou.order.mapper.OrderDetailMapper;
import com.leyou.order.mapper.OrderLogisticsMapper;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.utils.PayHelper;
import com.leyou.order.vo.OrderDetailVO;
import com.leyou.order.vo.OrderLogisticsVO;
import com.leyou.order.vo.OrderVO;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.AddressDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: xiang
 * @Date: 2019/9/2 20:43
 * @Description:
 */
@Service
@Slf4j
@Transactional
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private OrderLogisticsMapper logisticsMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private UserClient userCLient;

    @Autowired
    private ItemClient itemClient;

    @Transactional
    public Long createOrder(OrderDTO orderDTO) {
        // 1 写order
        Order order = new Order();

        // 1.1 订单编号
        long orderId = idWorker.nextId();
        order.setOrderId(orderId);

        // 1.2 登录用户
        Long userId = UserHolder.getUser().getId();
        order.setUserId(userId);

        // 1.3 金额相关信息
        List<CartDTO> carts = orderDTO.getCarts();
        // 获取所有sku的id
        List<Long> idList = carts.stream().map(CartDTO::getSkuId).collect(Collectors.toList());
        // 处理CartDTO为一个map， 其key是skuId；值是num
        Map<Long, Integer> numMap = carts.stream().collect(Collectors.toMap(CartDTO::getSkuId, CartDTO::getNum));
        // 1.3.1 查询sku
        List<SkuDTO> skuList = itemClient.querySkuByIds(idList);
        // 定义一个OrderDetail的集合
        List<OrderDetail> details = new ArrayList<>();
        // 1.3.2 计算金额的和
        long total = 0;
        for (SkuDTO sku : skuList) {
            int num = numMap.get(sku.getId());
            // 计算总金额
            total += sku.getPrice() * num;
            // 组装OrderDetail
            OrderDetail detail = new OrderDetail();
            detail.setOrderId(orderId);
            detail.setImage(StringUtils.substringBefore(sku.getImages(), ","));
            detail.setNum(num);
            detail.setSkuId(sku.getId());
            detail.setOwnSpec(sku.getOwnSpec());
            detail.setPrice(sku.getPrice());
            detail.setTitle(sku.getTitle());
            details.add(detail);
        }
        // 1.3.3 填写金额数据
        order.setTotalFee(total);
        order.setPostFee(0L);
        order.setPaymentType(orderDTO.getPaymentType());
        order.setActualFee(total + order.getPostFee()/* - 优惠金额*/);

        // 1.4 订单状态初始化
        order.setStatus(OrderStatusEnum.INIT.value());

        // 1.5 写order到数据库
        int count = orderMapper.insertSelective(order);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 2 写OrderDetail
        count = detailMapper.insertDetailList(details);
        if (count != details.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 3 写orderLogistics
        // 3.1.查询收货地址
        AddressDTO addr = userCLient.queryAddressById(userId, orderDTO.getAddressId());
        // 3.2.填写物流信息
        OrderLogistics logistics = BeanHelper.copyProperties(addr, OrderLogistics.class);
        logistics.setOrderId(orderId);

        count = logisticsMapper.insertSelective(logistics);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 4 减库存
        itemClient.minusStock(numMap);

        return orderId;
    }

    public OrderVO queryOrderById(Long id) {
        // 1.查询订单
        Order order = orderMapper.selectByPrimaryKey(id);
        if (order == null) {
            // 不存在
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        // 判断用户id是否正确
        Long userId = UserHolder.getUser().getId();
        if (!userId.equals(order.getUserId())) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }

        // 2. 查询订单详情
        OrderDetail detail = new OrderDetail();
        detail.setOrderId(id);
        List<OrderDetail> details = detailMapper.select(detail);
        if (CollectionUtils.isEmpty(details)) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }


        // 3.查询订单状态
        OrderLogistics logistics = logisticsMapper.selectByPrimaryKey(id);
        if (logistics == null) {
            // 不存在
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }

        // 4.封装数据
        OrderVO orderVO = BeanHelper.copyProperties(order, OrderVO.class);
        orderVO.setDetailList(BeanHelper.copyWithCollection(details, OrderDetailVO.class));
        orderVO.setLogistics(BeanHelper.copyProperties(logistics, OrderLogisticsVO.class));
        return orderVO;
    }

    @Autowired
    private PayHelper payHelper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public String CreatePayUrl(Long id) {
        //根据id查询order
        Order order = orderMapper.selectByPrimaryKey(id);
        if (order == null) {

            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        //判断订单状态
        if (order.getStatus() != 1) {
            //订单已经支付
            throw new LyException(ExceptionEnum.INVALID_ORDER_STATUS);
        }
        return payHelper.getPayUrl(id,"乐友商城优品",order.getActualFee());
    }
    @Transactional
    public void handleNotify(Map<String, String> data) {
        try {
            // 业务校验
            payHelper.checkResultCode(data);
            // 签名校验
            payHelper.checkSignature(data);
            // 订单状态校验（保证幂等，防止重复通知）
            String outTradeNo = data.get("out_trade_no");
            String totalFee = data.get("total_fee");
            if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(totalFee)) {
                // 数据有误
                throw new RuntimeException("订单编号或订单金额为空！");
            }
            Long orderId = Long.valueOf(outTradeNo);
            Order order = orderMapper.selectByPrimaryKey(orderId);
            if (!order.getStatus().equals(OrderStatusEnum.INIT.value())) {
                // 说明订单已经支付过了，属于重复通知，直接返回
                return;
            }
            // 订单金额校验
            Long total = Long.valueOf(totalFee);
            if (!total.equals(order.getActualFee())) {
                throw new RuntimeException("订单金额有误，我要报警了！");
            }
            // 修改订单状态
            Order record = new Order();
            record.setOrderId(orderId);
            record.setStatus(OrderStatusEnum.PAY_UP.value());
            record.setPayTime(new Date());
            int count = orderMapper.updateByPrimaryKeySelective(record);
            if (count != 1) {
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
            log.info("处理微信支付通知成功！{}", data);
            // TODO 删除Redis中的支付URL
        } catch (Exception e) {
            // 出现异常，通知处理失败
            log.error("处理微信支付通知失败，原因：{}", e.getMessage());
            throw new LyException(ExceptionEnum.INVALID_NOTIFY_PARAM);
        }
    }
    public Integer queryOrderStatus(Long orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if(order == null){
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return order.getStatus();
    }

}
